from server import app_auth
from flask import jsonify, Blueprint, request, g
from server.model.gym import Gym
from server.model.field import Field
from server.model.booking import Booking
from datetime import datetime

a_field = Blueprint('app/field', __name__)


@a_field.route('', methods=['GET'])
# @app_auth.login_required
def get_fields():
    """
                    @@@
                    #### Args:
                           {
                                page: 1,
                                limit: 20,
                                filter: {},
                                start_time: "2021-09-10",
                                end_time: "2021-09-12",
                            }
                    #### Returns::
                            {
                                'code': 20000,
                                'items': [u.to_dict() for u in field_list],
                            }
                """
    args = request.args
    gym_id = args.get('gym_id', type=int)
    select_date = args.get('date')
    print(select_date)

    try:
        gym = Gym.query.filter(Gym.id == gym_id).first()
        field_list = Field.query.filter(Field.gym_id == gym_id).all()
        bookings = Booking.query.filter(Booking.gym_id == gym_id, Booking.book_date == select_date).all()

        field_names = [u.name for u in field_list]

        book_dict = set()
        for booking in bookings:
            book_dict.add("%s_%s" % (booking.book_hour, booking.field_id))
        # 营业时间
        start_hour = int(gym.open_time.split(":")[0])
        end_hour = int(gym.close_time.split(":")[0])

        field_units = {}
        for hour in range(start_hour, end_hour):
            all_fields = []
            price = gym.count_price(hour, select_date)
            for field in field_list:
                temp = field.to_dict()
                temp['price'] = price
                book_key = "%s_%s" % (hour, field.id)
                if book_key in book_dict:
                    temp['booked'] = True
                all_fields.append(temp)
            field_units[hour] = all_fields

        return jsonify({
            'code': 20000,
            'message': 'success',
            'items': field_units,
            'start_hour': start_hour,
            'end_hour': end_hour,
            'field_names': field_names
        })
    except Exception as e:
        print("get fields error:", e)

    return jsonify({'code': 50001, 'message': "查询场地时发生错误"})
